package network;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TcpEchoServer {
    private ServerSocket serverSocket = null;

    public TcpEchoServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    public void start() throws IOException {
        System.out.println("服务器~~启动！！！");
        //引入线程池
        ExecutorService pool = Executors.newCachedThreadPool();
        while(true){

            //通过accept方法接通之后 才可以进行通信
            //如果没有客户端连接过来，就会阻塞
            Socket clientSocket = serverSocket.accept();
            //引入多线程
//            Thread t = new Thread(() -> {
//                processConnection(clientSocket);
//            });
//            t.start();
            //用线程池分配线程
            //解决频繁创建销毁的问题~~
            pool.submit(new Runnable() {
                @Override
                public void run() {
                    processConnection(clientSocket);
                }
            });
        }
    }

    //通过这个方法来处理一次连接，连接建立的过程中就会涉及到多次的请求响应交互
    private void processConnection(Socket clientSocket) {
        System.out.printf("[%s,%d] 客户端上线\n",clientSocket.getInetAddress(),
                clientSocket.getPort());
        //循环读取客户端请求 并返回响应
        //tcp是面向字节的，这里的字节流和文件操作的字节流完全一致
        //使用这些类和方法完成针对tcp socket的读写
        try(InputStream inputStream = clientSocket.getInputStream();
            OutputStream outputStream = clientSocket.getOutputStream()){
            //一般方法：
//            byte[] buffer = new byte[4096];
//            inputStream.read(buffer);
            //Scanner
            Scanner scanner = new Scanner(inputStream);
            while(true){
                if(!scanner.hasNext()){
                    System.out.printf("[%s,%d] 客户端下线\n",clientSocket.getInetAddress(),
                            clientSocket.getPort());
                    break;
                }
                //1. 读取请求并解析
                //隐藏的约定 客户端发来的请求有空白符 —— next()以空白符作为间隔
                String request = scanner.next();
                //2. 根据请求i计算响应
                String response = process(request);
                //3. 把响应返回给客户端
                //写法一  可以写回 不方便给响应中添加换行 （如果客户端也采用Scanner的方式读取）
                //outputStream.write(response.getBytes(),0,response.getBytes().length);
                //PrintWriter的方式 和Scanner对应
                PrintWriter printWriter = new PrintWriter(outputStream);
                printWriter.println(response);
                //手动冲刷缓冲区 确保数据真的发出去
                printWriter.flush();
                //日志
                System.out.printf("[%s,%d] req:%s,resp:%s\n",clientSocket.getInetAddress(),
                        clientSocket.getPort(),request,response);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                clientSocket.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
    public String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer server = new TcpEchoServer(9090);
        server.start();
    }
}
